package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.PmsPurchaseOrders;
import com.ruoyi.system.domain.PmsPurchaseRequisitions;
import com.ruoyi.system.mapper.PmsPurchaseOrdersMapper;
import com.ruoyi.system.mapper.PmsPurchaseRequisitionsMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.IPmsPurchaseRequisitionsService;
import com.ruoyi.system.utils.GetOrderNoUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.PmsPrOperationLogsBo;
import com.ruoyi.system.domain.vo.PmsPrOperationLogsVo;
import com.ruoyi.system.domain.PmsPrOperationLogs;
import com.ruoyi.system.mapper.PmsPrOperationLogsMapper;
import com.ruoyi.system.service.IPmsPrOperationLogsService;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 采购申请单操作日志Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-17
 */
@RequiredArgsConstructor
@Service
public class PmsPrOperationLogsServiceImpl implements IPmsPrOperationLogsService {

    private final PmsPrOperationLogsMapper baseMapper;


    private final PmsPrOperationLogsMapper pmsPrOperationLogsMapper;

    private final SysDeptMapper sysDeptMapper;

    private final PmsPurchaseRequisitionsMapper pmsPurchaseRequisitionsMapper;

    private final GetOrderNoUtil getOrderNoUtil;

    private final PmsPurchaseOrdersMapper pmsPurchaseOrdersMapper;

    /**
     * 查询采购申请单操作日志
     */
    @Override
    public PmsPrOperationLogsVo queryById(Long logId){
        return baseMapper.selectVoById(logId);
    }

    /**
     * 查询采购申请单操作日志列表
     */
    @Override
    public TableDataInfo<PmsPrOperationLogsVo> queryPageList(PmsPrOperationLogsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PmsPrOperationLogs> lqw = buildQueryWrapper(bo);
        Page<PmsPrOperationLogsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询采购申请单操作日志列表
     */
    @Override
    public List<PmsPrOperationLogsVo> queryList(PmsPrOperationLogsBo bo) {
        LambdaQueryWrapper<PmsPrOperationLogs> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PmsPrOperationLogs> buildQueryWrapper(PmsPrOperationLogsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PmsPrOperationLogs> lqw = Wrappers.lambdaQuery();
        lqw.eq(ObjectUtil.isNotNull(bo.getPrId()), PmsPrOperationLogs::getPrId, bo.getPrId());
        lqw.eq(StringUtils.isNotBlank(bo.getOperationType()), PmsPrOperationLogs::getOperationType, bo.getOperationType());
        lqw.eq(StringUtils.isNotBlank(bo.getOperationDesc()), PmsPrOperationLogs::getOperationDesc, bo.getOperationDesc());
        lqw.eq(ObjectUtil.isNotNull(bo.getOperatorId()), PmsPrOperationLogs::getOperatorId, bo.getOperatorId());
        lqw.like(StringUtils.isNotBlank(bo.getOperatorName()), PmsPrOperationLogs::getOperatorName, bo.getOperatorName());
        lqw.eq(StringUtils.isNotBlank(bo.getOperatorRole()), PmsPrOperationLogs::getOperatorRole, bo.getOperatorRole());
        lqw.eq(StringUtils.isNotBlank(bo.getFromStatus()), PmsPrOperationLogs::getFromStatus, bo.getFromStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getToStatus()), PmsPrOperationLogs::getToStatus, bo.getToStatus());
        lqw.eq(bo.getCreateTime() != null, PmsPrOperationLogs::getCreateTime, bo.getCreateTime());
        lqw.eq(bo.getParentLogId() != null, PmsPrOperationLogs::getParentLogId, bo.getParentLogId());
        return lqw;
    }

    /**
     * 新增采购申请单操作日志
     */
    @Override
    public Boolean insertByBo(PmsPrOperationLogsBo bo) {
        PmsPrOperationLogs add = BeanUtil.toBean(bo, PmsPrOperationLogs.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setLogId(add.getLogId());
        }
        return flag;
    }

    /**
     * 修改采购申请单操作日志
     */
    @Override
    public Boolean updateByBo(PmsPrOperationLogsBo bo) {
        PmsPrOperationLogs update = BeanUtil.toBean(bo, PmsPrOperationLogs.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PmsPrOperationLogs entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除采购申请单操作日志
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    public int insertLogByBo(PmsPurchaseRequisitions pmsPurchaseRequisitions){

        //判断是不是财务部的
        SysDept sysDept = sysDeptMapper.selectById(LoginHelper.getDeptId());
        if("FINANCE".equals(sysDept.getDeptCode())){
            initializePmsPrOperationLogsBo(pmsPurchaseRequisitions);
            int i = pmsPurchaseRequisitionsMapper.updatePmsPurchaseRequisitions(pmsPurchaseRequisitions);
            //需要新增一条采购订单的数据
            PmsPurchaseOrders pmsPurchaseOrders = new PmsPurchaseOrders();

            pmsPurchaseOrders.setPoCode(getOrderNoUtil.getOrderNo("PO-"));

            pmsPurchaseOrders.setPrId(pmsPurchaseRequisitions.getPrId());
            pmsPurchaseOrders.setPrCode(pmsPurchaseRequisitions.getPrCode());
            pmsPurchaseOrders.setOrderDate(new Date());
            pmsPurchaseOrders.setTotalAmount(pmsPurchaseRequisitions.getTotalAmount());
            pmsPurchaseOrders.setCreatedBy(LoginHelper.getUserId());
            pmsPurchaseOrders.setCreateTime(new Date());

            pmsPurchaseOrdersMapper.insert(pmsPurchaseOrders);
        }else {
            initializePmsPrOperationLogsBo(pmsPurchaseRequisitions);
        }

        return 1;
    }

    public void initializePmsPrOperationLogsBo(PmsPurchaseRequisitions pmsPurchaseRequisitions){
        PmsPrOperationLogsBo pmsPrOperationLogsBo = new PmsPrOperationLogsBo();
        pmsPrOperationLogsBo.setPrId(pmsPurchaseRequisitions.getPrId());
        pmsPrOperationLogsBo.setOperationType(pmsPurchaseRequisitions.getStatus());
        pmsPrOperationLogsBo.setOperationDesc(pmsPurchaseRequisitions.getRemark());
        pmsPrOperationLogsBo.setOperatorId(LoginHelper.getUserId());
        pmsPrOperationLogsBo.setOperatorName(LoginHelper.getNickName());

        PmsPrOperationLogs pmsPrOperationLogs = pmsPrOperationLogsMapper.selectOne(new LambdaQueryWrapper<PmsPrOperationLogs>()
            .eq(PmsPrOperationLogs::getPrId, pmsPurchaseRequisitions.getPrId())
            .orderByDesc(PmsPrOperationLogs::getCreateTime)
            .last("LIMIT 1")
        );
        if(ObjectUtils.isEmpty(pmsPrOperationLogs)){
            pmsPrOperationLogsBo.setFromStatus(null);
            pmsPrOperationLogsBo.setParentLogId(null);
        }else {
            pmsPrOperationLogsBo.setFromStatus(pmsPrOperationLogs.getOperationType());
            pmsPrOperationLogsBo.setParentLogId(pmsPrOperationLogs.getLogId());
        }
        pmsPrOperationLogsBo.setToStatus(pmsPurchaseRequisitions.getStatus());
        pmsPrOperationLogsBo.setCreateTime(new Date());

        pmsPrOperationLogsBo.setDeptId(LoginHelper.getDeptId());

        insertByBo(pmsPrOperationLogsBo);
    }
}
